package com.ag.answergames.service.question.impl;

import com.ag.answergames.entity.*;
import com.ag.answergames.mapper.question.*;
import com.ag.answergames.service.answerlog.AnswerLogService;
import com.ag.answergames.service.question.QuestionService;
import com.ag.answergames.util.SnowflakeIdWorkerController;
import com.ag.answergames.vo.*;
import com.ag.answergames.vo.common.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private WrongQuestionMapper wrongQuestionMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private GradeMapper gradeMapper;

    @Autowired
    private SubjectMapper subjectMapper;

    @Autowired
    private AnswerLogService answerLogService;

    @Autowired
    private AnswerCorrectCountMapper answerCorrectCountMapper;

    @Autowired
    private SnowflakeIdWorkerController snowflakeIdWorkerController;


    /**
     * 一条数据一条数据的查询返回
     *
     * @param questionStoreVO
     * @return
     */
    @Override
    public Result<QuestionEntity> findOnlyOne(QuestionStoreVO questionStoreVO) {

        QueryWrapper<QuestionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("grade_code",questionStoreVO.getGradeCode())
                .eq("subject_code",questionStoreVO.getSubjectCode());

        //设置分页以及煤业显示条数
        IPage<QuestionEntity> iPage = new Page<>(getQuestionPageRandom(questionStoreVO.getGradeCode(),questionStoreVO.getSubjectCode()), 1);

        //查询到数据放在了questionEntityIPage的recode里面
        IPage<QuestionEntity> questionEntityIPage = questionMapper.selectPage(iPage, queryWrapper);

        //判断数据是否查到，如果查到，判断是否已经被逻辑删除
        if (questionEntityIPage != null &&
                questionEntityIPage.getRecords().size() != 0 &&
                questionEntityIPage.getRecords().get(0).getIsDeleted() != 1) {

            AnswerQuestionRollbackVO answerQuestionRebackVO = new AnswerQuestionRollbackVO();

            answerQuestionRebackVO.setQuestionId(questionEntityIPage.getRecords().get(0).getId());
            answerQuestionRebackVO.setTitle(questionEntityIPage.getRecords().get(0).getTitle());
            answerQuestionRebackVO.setAnswerA(questionEntityIPage.getRecords().get(0).getAnswerA());
            answerQuestionRebackVO.setAnswerB(questionEntityIPage.getRecords().get(0).getAnswerB());
            answerQuestionRebackVO.setAnswerC(questionEntityIPage.getRecords().get(0).getAnswerC());
            answerQuestionRebackVO.setAnswerD(questionEntityIPage.getRecords().get(0).getAnswerD());
            answerQuestionRebackVO.setAnswerCorrect(questionEntityIPage.getRecords().get(0).getAnswerCorrect());
            answerQuestionRebackVO.setDescribe(questionEntityIPage.getRecords().get(0).getTitleDescribe());

            return Result.success(answerQuestionRebackVO);
        }

        return Result.failed("没有查到数据或已经被删除！！！");
    }


    /**
     * 生成随机题库分页page
     * @return
     */
    private int getQuestionPageRandom(int grade, int subject) {
        //随机页数
        QueryWrapper<QuestionEntity> entityQueryWrapper = new QueryWrapper<>();
        entityQueryWrapper.eq("grade_code",grade)
                .eq("subject_code",subject);
        List<QuestionEntity> questionEntities = questionMapper.selectList(entityQueryWrapper);
        int size = questionEntities.size();
        return new Random().nextInt(size)+1;
    }


    /**
     * 生成随机错题集分页page(待会儿在做)
     * @return
     */
    private int getWrongPageRandom(long userId, int grade, int subject) {
        //随机页数
        QueryWrapper<WrongQuestionEntity> entityQueryWrapper = new QueryWrapper<>();
        entityQueryWrapper
                .eq("user_id", userId)
                .eq("grade_code",grade)
                .eq("subject_code",subject);
        List<WrongQuestionEntity> wrongQuestionEntityList = wrongQuestionMapper.selectList(entityQueryWrapper);
        int size = wrongQuestionEntityList.size();
        return new Random().nextInt(size);
    }


    /**
     * 一次查找一条错题集里面的数据
     * @param questionWrongVO
     * @return
     */
    @Override
    public Result<QuestionEntity> findOneWrong(QuestionWrongVO questionWrongVO) {

        QueryWrapper<WrongQuestionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", questionWrongVO.getUserId())
                .eq("grade_code",questionWrongVO.getGradeCode())
                .eq("subject_code",questionWrongVO.getSubjectCode())
                .ge("wrong_count",1);

        //设置分页以及每页显示条数
        IPage<WrongQuestionEntity> iPage = new Page<>(getWrongPageRandom(questionWrongVO.getUserId(), questionWrongVO.getGradeCode(),questionWrongVO.getSubjectCode()), 1);

        //查询到数据放在了questionEntityIPage的recode里面
        IPage<WrongQuestionEntity> questionEntityIPage = wrongQuestionMapper.selectPage(iPage, queryWrapper);

        //判断数据是否查到，如果查到，判断是否已经被逻辑删除
        if (questionEntityIPage != null &&
                questionEntityIPage.getRecords().size() != 0 &&
                questionEntityIPage.getRecords().get(0).getWrongCount() != 0 &&
                questionEntityIPage.getRecords().get(0).getIsDeleted() != 1) {

            //通过错题id到题库里面查找
            QueryWrapper<QuestionEntity> toFindQuestion = new QueryWrapper<>();
            toFindQuestion.eq("id",questionEntityIPage.getRecords().get(0).getQuestionId());
            QuestionEntity questionEntity = questionMapper.selectOne(toFindQuestion);

            AnswerQuestionWrongRollbackVO answerQuestionWrongRollbackVO = new AnswerQuestionWrongRollbackVO();

            answerQuestionWrongRollbackVO.setQuestionId(questionEntity.getId());
            answerQuestionWrongRollbackVO.setTitle(questionEntity.getTitle());
            answerQuestionWrongRollbackVO.setAnswerA(questionEntity.getAnswerA());
            answerQuestionWrongRollbackVO.setAnswerB(questionEntity.getAnswerB());
            answerQuestionWrongRollbackVO.setAnswerC(questionEntity.getAnswerC());
            answerQuestionWrongRollbackVO.setAnswerD(questionEntity.getAnswerD());
            answerQuestionWrongRollbackVO.setAnswerCorrect(questionEntity.getAnswerCorrect());
            answerQuestionWrongRollbackVO.setDescribe(questionEntity.getTitleDescribe());
            answerQuestionWrongRollbackVO.setWrongCount(questionEntityIPage.getRecords().get(0).getWrongCount());

            return Result.success(answerQuestionWrongRollbackVO);
        }

        AnswerQuestionWrongRollbackVO answerQuestionWrongRollbackVO=new AnswerQuestionWrongRollbackVO();
        answerQuestionWrongRollbackVO.setAnswerA("");
        answerQuestionWrongRollbackVO.setAnswerB("");
        answerQuestionWrongRollbackVO.setAnswerC("");
        answerQuestionWrongRollbackVO.setAnswerD("");
        answerQuestionWrongRollbackVO.setTitle("");
        return Result.success(answerQuestionWrongRollbackVO);
    }


    /**
     * 添加到错题集
     * 未完成，还差一个更新wrong_count（需要用到update的功能）
     *
     * @param userId
     * @param wrongId
     * @param choose
     * @return
     */
    @Override
    public Result add(QuestionCheckRequestVO questionCheckRequestVO) {

        int insert = addQuestionToWrong(questionCheckRequestVO);

        if (insert > 0) {
            return Result.success(insert);
        }
        return Result.failed("添加失败");
    }


    /**
     * 添加试题到错题集
     *
     * @param userId
     * @param wrongId
     * @param choose
     * @return
     */
    private int addQuestionToWrong(QuestionCheckRequestVO questionCheckRequestVO) {
        long id = snowflakeIdWorkerController.nextId();

        WrongQuestionEntity wrongQuestionEntity = new WrongQuestionEntity();

        wrongQuestionEntity.setId(id);
        wrongQuestionEntity.setUserId(questionCheckRequestVO.getUserId());
        wrongQuestionEntity.setQuestionId(questionCheckRequestVO.getQuestionId());
        wrongQuestionEntity.setGradeCode(questionCheckRequestVO.getGradeCode());
        wrongQuestionEntity.setSubjectCode(questionCheckRequestVO.getSubjectCode());
        wrongQuestionEntity.setChoose(questionCheckRequestVO.getChoose());
        wrongQuestionEntity.setWrongCount(1);

        return wrongQuestionMapper.insert(wrongQuestionEntity);
    }


    /**
     * 逻辑删除试题库试题
     * 删除错误的试题的标记isDeleted
     *
     * @param userId
     * @param questionId
     * @param isDeleted
     * @return
     */
    @Override
    public Result questionIsDeleted(long userId, long questionId, int isDeleted) {
        QuestionEntity questionEntity = new QuestionEntity();
        questionEntity.setUserId(userId);
        questionEntity.setId(questionId);
        questionEntity.setIsDeleted(isDeleted);


        if (isDeleted == 1) {
            //删除题库错误试题
            int updateStoreById = questionMapper.updateById(questionEntity);
            return Result.success(updateStoreById);
        }

        return Result.failed("删除失败！！！");
    }


    /**
     * 错题次数更新
     * 删除用户错题集的标记wrongCount
     *
     * @param userId
     * @param questionId
     * @param wrong
     * @param choose
     * @return
     */
    @Override
    public Result wrongQuestionCount(QuestionCheckRequestVO questionCheckRequestVO) {

        //通过userId,questionId在wrong_question数据表中查询得到id
        QueryWrapper<WrongQuestionEntity> wrongQuestionEntityQueryWrapper = new QueryWrapper<>();
        wrongQuestionEntityQueryWrapper.eq("user_id", questionCheckRequestVO.getUserId())
                .eq("question_id", questionCheckRequestVO.getQuestionId());

        WrongQuestionEntity wrongQuestionEntity = wrongQuestionMapper.selectOne(wrongQuestionEntityQueryWrapper);

        //答题错误
        if (!questionCheckRequestVO.getAnswer()) {

            //判断是否在用户对用的错题集里，在的话wrongCount+1
            //错题集里面有这条数据
            if (wrongQuestionEntity != null) {
                Long answerWrongQuestionId = wrongQuestionEntity.getId();

                //通过answerWrongQuestionId更新答错次数
                Integer wrongCount = wrongQuestionEntity.getWrongCount();

                if (wrongCount >= 0 && wrongCount < 3) {
                    wrongQuestionEntity.setWrongCount(wrongCount + 1);
                    wrongQuestionEntity.setId(answerWrongQuestionId);
                    int i = wrongQuestionMapper.updateById(wrongQuestionEntity);
                    return Result.success(i);
                }

                //答题错误次数大于3次,不做修改
                return Result.success("答错次数大于3次");
            }

            //加入到错题集
            //答错且错题集中没有这道题
            return Result.success(addQuestionToWrong(questionCheckRequestVO));

        }

        //答题正确
        //判单答题是否有过错误，有的话错误次数减一（还可以添加correctCount答对次数）
        if (wrongQuestionEntity != null &&
                wrongQuestionEntity.getWrongCount() > 0) {

            wrongQuestionEntity.setWrongCount(wrongQuestionEntity.getWrongCount() - 1);
            wrongQuestionEntity.setId(wrongQuestionEntity.getId());
            int i = wrongQuestionMapper.updateById(wrongQuestionEntity);
            return Result.success(i);
        }

        return Result.success("查询下一道试题");
    }


    /**
     * 检测选择答案是否正确
     *
     * @param userId
     * @param questionId
     * @param choose
     * @return
     */
    @Override
    public Result checkChoose(QuestionCheckRequestVO questionCheckRequestVO) {

        QueryWrapper<QuestionEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", questionCheckRequestVO.getQuestionId());

        QuestionEntity questionEntity = questionMapper.selectOne(queryWrapper);


        boolean wrong =false;

        //选择正确
        if (questionCheckRequestVO.getChoose().equals(questionEntity.getAnswerCorrect())) {

            //统计每个用户答题正确次数
            QueryWrapper<AnswerCorrectEntity> entityQueryWrapper = new QueryWrapper<>();
            entityQueryWrapper.eq("user_id",questionCheckRequestVO.getUserId());

            AnswerCorrectEntity answerCorrectEntity = answerCorrectCountMapper.selectOne(entityQueryWrapper);

            AnswerCorrectEntity reset = new AnswerCorrectEntity();
            //判断统计表中有没有这个用户
            if (answerCorrectEntity == null){

                //没有这个用户,天价到统计表中
                reset.setId(snowflakeIdWorkerController.nextId());
                reset.setCorrectCount(1);
                answerCorrectCountMapper.insert(reset);
            } else {

                //有这个用户，统计字段加1
                reset.setCorrectCount(answerCorrectEntity.getCorrectCount()+1);
                answerCorrectCountMapper.update(reset,entityQueryWrapper);
            }

            wrong = true;
        }

        questionCheckRequestVO.setAnswer(wrong);
        wrongQuestionCount(questionCheckRequestVO);

        return Result.success(wrong);
    }

    /**
     * 查找所有班级
     *
     * @return
     */
    @Override
    public Result findAllGrade() {
        QueryWrapper<GradeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("grade_name");
        List<GradeEntity> gradeEntityList = gradeMapper.selectList(queryWrapper);

        int gradeLenght = gradeEntityList.size();
        List<String> list = new ArrayList<>();
        for (GradeEntity grade:gradeEntityList
             ) {
            list.add(grade.getGradeName());
        }


        if (list.size() > 0) {
            return Result.success(list);
        }
        return Result.failed("没有找到！！！");
    }

    /**
     * 查找所有的学科
     *
     * @return
     */
    @Override
    public Result findAllSubject() {
        QueryWrapper<SubjectEntity> queryWrapper = new QueryWrapper<>();
        List<SubjectEntity> subjectEntityList = subjectMapper.selectList(queryWrapper);
        queryWrapper.select("subject_name");

        int gradeLenght = subjectEntityList.size();
        List<String> list = new ArrayList<>();
        for (SubjectEntity suject:subjectEntityList
        ) {
            list.add(suject.getSubjectName());
        }

        if (list.size() > 0) {
            return Result.success(list);
        }
        return Result.failed("没有找到！！！");
    }

}
